import json
import os
from datetime import datetime

from storage_manager import LAYOUT_FILE_PATH

# ------------------------------ 管理员功能模块（新增座位管理功能）------------------------------
ADMIN_PASSWORD = "admin123"

def verify_admin():
    password = input("请输入管理员密码: ")
    return password == ADMIN_PASSWORD

def initialize_daily_seats(target_date, all_reservations):
    """重置某日预约数据"""
    updated_reservations = [r for r in all_reservations if r["date"] != target_date]
    return updated_reservations

def save_layout_config_to_file(layout_info):
    """保存座位布局到文件"""
    try:
        os.makedirs(os.path.dirname(LAYOUT_FILE_PATH), exist_ok=True)
        with open(LAYOUT_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(layout_info, f, indent=4, ensure_ascii=False)
        print("座位布局已保存。")
        return True
    except IOError:
        print("保存座位布局时出错。")
        return False

def manage_seat_layout(layout_info):
    """座位布局管理功能（增、删、改）"""
    print("\n=== 座位布局管理 ===")
    print("当前座位布局:")
    print(f"座位区域: {', '.join(layout_info['seat_prefix'])}")
    print(f"每区域座位数: {layout_info['seats_per_prefix_row']}")
    print(f"时段: {', '.join(layout_info['timeslots'])}")

    while True:
        print("\n操作选项:")
        print("1. 添加座位区域（如增加F区）")
        print("2. 修改每区域座位数")
        print("3. 删除座位区域")
        print("4. 返回上级菜单")
        choice = input("请选择操作 (1-4): ")

        if choice == "1":
            new_prefix = input("请输入新座位区域编号（如F）: ").strip().upper()
            if new_prefix in layout_info['seat_prefix']:
                print(f"区域 {new_prefix} 已存在。")
                continue
            layout_info['seat_prefix'].append(new_prefix)
            print(f"已添加座位区域 {new_prefix}。")
            save_layout_config_to_file(layout_info)

        elif choice == "2":
            try:
                new_count = int(input("请输入每区域新座位数（如8）: "))
                if new_count <= 0:
                    raise ValueError
                layout_info['seats_per_prefix_row'] = new_count
                print(f"每区域座位数已修改为 {new_count}。")
                save_layout_config_to_file(layout_info)
            except ValueError:
                print("请输入有效的正整数。")

        elif choice == "3":
            prefix_to_remove = input("请输入要删除的座位区域编号（如E）: ").strip().upper()
            if prefix_to_remove not in layout_info['seat_prefix']:
                print(f"区域 {prefix_to_remove} 不存在。")
                continue
            layout_info['seat_prefix'].remove(prefix_to_remove)
            print(f"已删除座位区域 {prefix_to_remove}。")
            save_layout_config_to_file(layout_info)

        elif choice == "4":
            return layout_info
        else:
            print("无效的选择，请重新输入。")

def admin_menu_interaction(all_reservations, layout_info):
    if not verify_admin():
        print("密码错误，权限不足。")
        return None, layout_info

    print("\n=== 管理员菜单 ===")
    print("1. 重置某日座位数据")
    print("2. 管理座位布局（新增/修改/删除座位）")  # 新增功能项
    print("3. 返回主菜单")

    while True:
        choice = input("请选择操作 (1-3): ")

        if choice == "1":
            # 重置预约数据逻辑（原有代码）
            while True:
                date_str = input("请输入要重置的日期 (YYYY-MM-DD): ")
                try:
                    datetime.strptime(date_str, "%Y-%m-%d")
                    break
                except ValueError:
                    print("日期格式无效，请重新输入。")

            confirm = input(f"确定要重置 {date_str} 的所有预约数据吗? (y/n): ").lower()
            if confirm == 'y':
                updated_reservations = initialize_daily_seats(date_str, all_reservations)
                print(f"{date_str} 的座位数据已重置。")
                return updated_reservations, layout_info
            else:
                print("操作已取消。")
                return all_reservations, layout_info

        elif choice == "2":
            # 调用座位布局管理功能（新增）
            layout_info = manage_seat_layout(layout_info)
            return all_reservations, layout_info  # 返回更新后的布局数据

        elif choice == "3":
            return all_reservations, layout_info  # 退出管理员菜单

        else:
            print("无效的选择，请重新输入。")